package fafu.edu.wcy.springdemo.controller;

import fafu.edu.wcy.springdemo.config.WebConfig;
import fafu.edu.wcy.springdemo.entity.CustomerMessage;
import fafu.edu.wcy.springdemo.entity.FileStore;
import fafu.edu.wcy.springdemo.entity.User;
import fafu.edu.wcy.springdemo.service.ICustomerMessageService;
import fafu.edu.wcy.springdemo.service.impl.UserService;
import fafu.edu.wcy.springdemo.utils.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RequestMapping("/user")
@RestController
// @RestController
public class UserController {

    @RequestMapping("index")
    public User index(@RequestBody User user){
        return user;
    }

    @Autowired
    private ICustomerMessageService customerMessageService;

    @RequestMapping("commit")
    public MessageUtils commit(@RequestBody CustomerMessage customerMessage, HttpServletRequest request){
        MessageUtils message = new MessageUtils();
        System.out.println(customerMessage);
        customerMessageService.saveCustomerMessage(customerMessage);
        message.setMessage("保存数据");
        message.setData(customerMessage.getId());
        return message;
    }

    @RequestMapping("findCustomerMessage")
    public MessageUtils findCustomerMessage(@RequestBody CustomerMessage customerMessage, HttpServletRequest request){
        MessageUtils message = new MessageUtils<List<CustomerMessage>>();
        System.out.println(customerMessage);
        List<CustomerMessage> customerMessage1 = customerMessageService.findCustomerMessage(customerMessage);

        message.setMessage("保存数据");
        message.setData(customerMessage1);
        return message;
    }
    /**
     * 文件上传具体实现方法;
     *
     * @param fl
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("fl") MultipartFile fl,@RequestParam("id") String id) {
        System.out.println("留言id"+id);
        if (id==null||id.equals("")){
            return "文件上传失败，文件无法存储";
        }
        FileStore fileStore = new FileStore();
        fileStore.setName(fl.getOriginalFilename());
        // 生成id乱码
        customerMessageService.saveFileStore(fileStore);
        System.out.println("上传文件"+fl+fileStore);
        if (!fl.isEmpty()) {
            try {
                /*
                 * 这段代码执行完毕之后，图片上传到了工程的跟路径； 大家自己扩散下思维，如果我们想把图片上传到
                 * d:/files大家是否能实现呢？ 等等;
                 * 这里只是简单一个例子,请自行参考，融入到实际中可能需要大家自己做一些思考，比如： 1、文件路径； 2、文件名；
                 * 3、文件格式; 4、文件大小的限制;
                 */
                File tempFile = new File(WebConfig.filename);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(WebConfig.filename+
                                fileStore.getId())));


                System.out.println(fl.getName());
                out.write(fl.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }

            CustomerMessage customerMessage = new CustomerMessage();
            customerMessage.setId(id);
            customerMessage.setFileId(fileStore.getId());
            Integer i = customerMessageService.updateCustomerMessage(customerMessage);
            if (i>0){
                return "上传成功";
            }else {
                return "文件上传成功，数据库失效";
            }

        } else {
            return "上传失败，因为文件是空的.";
        }
    }
    /**
     * @param path     指想要下载的文件的路径
     * @param response
     * @功能描述 下载文件:将输入流中的数据循环写入到响应输出流中，而不是一次性读取到内存
     */
    @RequestMapping("downloadLocal")
    public void  downloadLocal(@RequestParam String path, HttpServletResponse response) throws IOException {
        // 读到流中
        System.out.println("下载文件");
        InputStream inputStream = new FileInputStream(WebConfig.filename+path);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(path).getName();
        // TODO: "filename.pdf" 之后去制作修改
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("filename.pdf", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }


}
